<template>
  <C_Layout>
    <view class="component-management p-4">
      <!-- 页面说明 -->
      <view class="intro-section mb-6">
        <view
          class="intro-card p-4 bg-gradient-to-r from-blue-500 to-purple-600 rounded-xl text-white"
        >
          <view class="flex items-center mb-2">
            <C_Icon name="i-mdi-package-variant" :size="32" color="white" />
            <text class="ml-3 text-lg font-bold">组件演示中心</text>
          </view>
          <text class="text-sm opacity-90">
            这里是项目中所有组件的演示页面集合，你可以直观地查看每个组件的效果和用法
          </text>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-section mb-6 text-center py-8">
        <C_Icon
          name="i-mdi-loading"
          :size="32"
          color="#999"
          class="animate-spin"
        />
        <text class="block mt-2 text-sm text-gray-500"
          >正在加载组件数据...</text
        >
      </view>

      <!-- 错误提示 -->
      <view
        v-else-if="error"
        class="error-section mb-6 p-4 bg-red-50 rounded-lg border border-red-200"
      >
        <view class="flex items-center">
          <C_Icon name="i-mdi-alert-circle" :size="20" color="#ef4444" />
          <text class="ml-2 text-sm text-red-600">{{ error }}</text>
        </view>
        <button
          class="text-xs text-blue-600 underline mt-2"
          @click="loadComponentData"
        >
          重新加载
        </button>
      </view>

      <!-- 主要内容 -->
      <template v-else>
        <!-- 数据更新提示 -->
        <view v-if="dataInfo.generatedAt" class="data-info mb-4">
          <view
            class="flex items-center justify-between p-3 bg-blue-50 rounded-lg"
          >
            <view class="flex items-center">
              <C_Icon name="i-mdi-information" :size="16" color="#2563eb" />
              <text class="ml-2 text-xs text-blue-600">
                数据更新: {{ formatTime(dataInfo.generatedAt) }} |
                {{ scanModeText }}
              </text>
            </view>
            <button
              class="text-xs text-blue-600 underline"
              @click="loadComponentData"
            >
              刷新数据
            </button>
          </view>
        </view>

        <!-- 统计信息 -->
        <view class="stats-overview mb-6">
          <view class="stats-grid grid grid-cols-4 gap-3">
            <view
              class="stat-card p-3 bg-white rounded-lg shadow-sm text-center"
            >
              <text class="stat-number text-xl font-bold text-blue-600">{{
                componentList.length
              }}</text>
              <text class="stat-label block text-xs text-gray-500 mt-1"
                >组件总数</text
              >
            </view>
            <view
              class="stat-card p-3 bg-white rounded-lg shadow-sm text-center"
            >
              <text class="stat-number text-xl font-bold text-green-600">{{
                completedCount
              }}</text>
              <text class="stat-label block text-xs text-gray-500 mt-1"
                >已完成</text
              >
            </view>
            <view
              class="stat-card p-3 bg-white rounded-lg shadow-sm text-center"
            >
              <text class="stat-number text-xl font-bold text-orange-600">{{
                developingCount
              }}</text>
              <text class="stat-label block text-xs text-gray-500 mt-1"
                >开发中</text
              >
            </view>
            <view
              class="stat-card p-3 bg-white rounded-lg shadow-sm text-center"
            >
              <text class="stat-number text-xl font-bold text-purple-600"
                >{{ completionRate }}%</text
              >
              <text class="stat-label block text-xs text-gray-500 mt-1"
                >完成率</text
              >
            </view>
          </view>
        </view>

        <!-- 组件分类筛选 -->
        <view class="category-section mb-6">
          <view class="section-title mb-4 text-lg font-bold text-gray-800"
            >🏷️ 组件分类</view
          >

          <view class="category-grid grid grid-cols-2 gap-3 mb-4">
            <view
              v-for="category in categories"
              :key="category.key"
              class="category-card p-3 bg-white rounded-lg shadow-sm border-l-4 cursor-pointer"
              :class="{ 'category-active': selectedCategory === category.key }"
              :style="{ borderLeftColor: category.color }"
              @click="filterByCategory(category.key)"
            >
              <view class="flex items-center justify-between">
                <view class="flex items-center">
                  <C_Icon
                    :name="category.icon"
                    :size="18"
                    :color="category.color"
                  />
                  <text class="ml-2 font-semibold text-gray-800 text-sm">{{
                    category.name
                  }}</text>
                </view>
                <view class="count-badge px-2 py-1 bg-gray-100 rounded-full">
                  <text class="text-xs text-gray-600">{{
                    category.count
                  }}</text>
                </view>
              </view>
              <text class="text-xs text-gray-500 mt-1">{{
                category.desc
              }}</text>
            </view>
          </view>

          <!-- 筛选按钮 -->
          <view class="filter-actions flex items-center gap-2">
            <text class="text-sm text-gray-600">筛选:</text>
            <button
              class="filter-btn px-3 py-1 text-xs rounded-full transition-all"
              :class="
                selectedCategory === 'all'
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-200 text-gray-600'
              "
              @click="showAllComponents"
            >
              全部 ({{ componentList.length }})
            </button>
            <button
              class="filter-btn px-3 py-1 text-xs rounded-full transition-all"
              :class="
                statusFilter === 'completed'
                  ? 'bg-green-500 text-white'
                  : 'bg-gray-200 text-gray-600'
              "
              @click="filterByStatus('completed')"
            >
              已完成 ({{ completedCount }})
            </button>
            <button
              class="filter-btn px-3 py-1 text-xs rounded-full transition-all"
              :class="
                statusFilter === 'developing'
                  ? 'bg-orange-500 text-white'
                  : 'bg-gray-200 text-gray-600'
              "
              @click="filterByStatus('developing')"
            >
              开发中 ({{ developingCount }})
            </button>
          </view>
        </view>

        <!-- 组件列表 -->
        <view class="components-section">
          <view class="section-header flex items-center justify-between mb-4">
            <view class="section-title text-lg font-bold text-gray-800">
              🧩 {{ currentSectionTitle }} ({{ filteredComponents.length }})
            </view>
          </view>

          <view class="components-grid space-y-3">
            <view
              v-for="component in filteredComponents"
              :key="component.id"
              class="component-card p-4 bg-white rounded-lg shadow-sm border border-gray-100 cursor-pointer"
              @click="navigateToDemo(component)"
            >
              <view class="card-header flex items-start justify-between mb-3">
                <view class="component-info flex items-center flex-1">
                  <!-- 序号 -->
                  <view
                    class="component-number mr-3 w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center"
                  >
                    <text class="text-xs text-white font-bold">{{
                      component.order
                    }}</text>
                  </view>

                  <!-- 图标 -->
                  <view
                    class="icon-wrapper w-10 h-10 rounded-lg flex items-center justify-center mr-3"
                    :style="{ backgroundColor: component.color + '20' }"
                  >
                    <C_Icon
                      :name="component.icon"
                      :size="20"
                      :color="component.color"
                    />
                  </view>

                  <!-- 组件信息 -->
                  <view class="flex-1">
                    <view class="flex items-center mb-1">
                      <text
                        class="component-name text-base font-bold text-gray-800"
                        >{{ component.name }}</text
                      >
                      <view
                        class="status-badge ml-2 px-2 py-1 rounded-full text-xs"
                        :class="getStatusClass(component.status)"
                      >
                        {{ getStatusText(component.status) }}
                      </view>
                    </view>
                    <text
                      class="component-desc text-sm text-gray-600 leading-relaxed"
                    >
                      {{ component.description }}
                    </text>
                    <text
                      class="component-path text-xs text-gray-400 mt-1 block"
                      >{{ component.path }}</text
                    >
                  </view>
                </view>

                <!-- 右侧操作 -->
                <view class="card-actions">
                  <C_Icon
                    :name="
                      component.hasDemo
                        ? 'i-mdi-play-circle'
                        : 'i-mdi-construction'
                    "
                    :size="24"
                    :color="component.hasDemo ? '#409eff' : '#f59e0b'"
                  />
                </view>
              </view>

              <!-- 底部信息 -->
              <view class="card-footer">
                <view
                  class="component-tags flex flex-wrap gap-2 mb-3"
                  v-if="component.tags"
                >
                  <text
                    v-for="tag in component.tags"
                    :key="tag"
                    class="tag text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded"
                  >
                    {{ tag }}
                  </text>
                </view>

                <view class="component-meta flex items-center justify-between">
                  <view class="meta-left flex items-center gap-4">
                    <view
                      class="meta-item flex items-center"
                      v-if="component.category"
                    >
                      <C_Icon name="i-mdi-folder" :size="14" color="#999" />
                      <text class="ml-1 text-xs text-gray-500">{{
                        getCategoryName(component.category)
                      }}</text>
                    </view>
                    <view
                      class="meta-item flex items-center"
                      v-if="component.version"
                    >
                      <C_Icon name="i-mdi-tag" :size="14" color="#999" />
                      <text class="ml-1 text-xs text-gray-500"
                        >v{{ component.version }}</text
                      >
                    </view>
                  </view>

                  <view class="meta-right">
                    <text class="text-xs text-gray-400">
                      {{ component.hasDemo ? "可体验" : "即将推出" }}
                    </text>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 空状态 -->
          <view
            v-if="filteredComponents.length === 0"
            class="empty-state py-12 text-center"
          >
            <C_Icon
              name="i-mdi-package-variant-closed"
              :size="48"
              color="#ddd"
            />
            <text class="empty-text block mt-4 text-gray-500">暂无组件</text>
            <text class="empty-desc block mt-2 text-sm text-gray-400">
              {{ getEmptyStateText() }}
            </text>
          </view>
        </view>

        <!-- 开发提示 -->
        <view class="dev-tip-section mt-8 mb-4">
          <view
            class="dev-tip-card p-4 bg-gradient-to-r from-green-400 to-blue-500 rounded-lg text-white"
          >
            <view class="flex items-center justify-between">
              <view>
                <text class="text-base font-bold">想要添加新的组件演示？</text>
                <text class="block text-sm mt-1 opacity-90">
                  联系开发团队或者按照文档规范创建新的演示页面
                </text>
              </view>
              <C_Icon name="i-mdi-plus-circle" :size="32" color="white" />
            </view>
          </view>
        </view>
      </template>
    </view>
  </C_Layout>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";

const loading = ref(true);
const error = ref("");
const componentList = ref([]);
const dataInfo = ref({});
const selectedCategory = ref("all");
const statusFilter = ref("all");

const categoryMap = {
  general: "通用",
  form: "表单",
  layout: "布局",
  navigation: "导航",
  display: "展示",
  feedback: "反馈",
};

const categoryIcons = {
  general: "i-mdi-cube-outline",
  form: "i-mdi-form-select",
  layout: "i-mdi-view-dashboard",
  navigation: "i-mdi-navigation",
  display: "i-mdi-view-list",
  feedback: "i-mdi-message-alert",
};

const categoryColors = {
  general: "#409eff",
  form: "#e6a23c",
  layout: "#67c23a",
  navigation: "#f56c6c",
  display: "#9c88ff",
  feedback: "#ff9f43",
};

const getCategoryName = (category) => categoryMap[category] || category;

const completedCount = computed(
  () => componentList.value.filter((item) => item.status === "completed").length
);

const developingCount = computed(
  () =>
    componentList.value.filter((item) => item.status === "developing").length
);

const completionRate = computed(() => {
  if (componentList.value.length === 0) return 0;
  return Math.round((completedCount.value / componentList.value.length) * 100);
});

const scanModeText = computed(() => {
  const mode = dataInfo.value.scanMode;
  if (mode === "backup") return "备用数据";
  if (mode === "intelligent") return "智能扫描";
  return "未知模式";
});

const categories = computed(() => {
  const stats = {};
  componentList.value.forEach((component) => {
    const category = component.category || "general";
    stats[category] = (stats[category] || 0) + 1;
  });

  const cats = [];
  Object.entries(stats).forEach(([key, count]) => {
    cats.push({
      key,
      name: getCategoryName(key),
      count,
      desc: `${count} 个组件`,
      icon: categoryIcons[key] || "i-mdi-folder",
      color: categoryColors[key] || "#999",
    });
  });

  return cats.sort((a, b) => b.count - a.count);
});

const filteredComponents = computed(() => {
  let result = componentList.value;

  // 按分类筛选
  if (selectedCategory.value !== "all") {
    result = result.filter(
      (component) => component.category === selectedCategory.value
    );
  }

  // 按状态筛选
  if (statusFilter.value !== "all") {
    result = result.filter(
      (component) => component.status === statusFilter.value
    );
  }

  return result;
});

const currentSectionTitle = computed(() => {
  const parts = [];

  if (selectedCategory.value !== "all") {
    parts.push(getCategoryName(selectedCategory.value));
  }

  if (statusFilter.value !== "all") {
    parts.push(statusFilter.value === "completed" ? "已完成" : "开发中");
  }

  if (parts.length === 0) {
    return "全部组件";
  }

  return parts.join(" - ");
});

const loadComponentData = async () => {
  loading.value = true;
  error.value = "";

  try {
    const componentsData = await import("@/../scripts/_data/components.js");
    const data = componentsData.default;
    componentList.value = data.components || [];
    dataInfo.value = data;
    console.log("组件数据加载成功:", data.components?.length || 0, "个组件");
  } catch (err) {
    console.warn("使用备用数据:", err.message);
    useBackupData();
  } finally {
    loading.value = false;
  }
};

const useBackupData = () => {
  const backupComponents = [
    {
      id: "c_header",
      name: "C_Header",
      order: "01",
      path: "/pages/demo/02-header/index",
      description: "统一头部导航组件，支持返回按钮、标题自定义、右侧操作等功能",
      icon: "i-mdi-page-layout-header",
      color: "#4ecdc4",
      category: "navigation",
      hasDemo: false,
      status: "developing",
      version: "1.2.0",
      tags: ["导航", "头部", "布局"],
    },
    {
      id: "c_icon",
      name: "C_Icon",
      order: "02",
      path: "/pages/demo/01-icon/index",
      description:
        "通用图标组件，支持UnoCSS、uView+、SVG、图片和自定义内容五种类型",
      icon: "i-mdi-palette",
      color: "#ff6b6b",
      category: "general",
      hasDemo: true,
      status: "completed",
      version: "1.0.0",
      tags: ["图标", "UnoCSS", "uView+", "多类型"],
    },
    {
      id: "c_layout",
      name: "C_Layout",
      order: "03",
      path: "/pages/demo/03-layout/index",
      description: "页面布局组件，提供统一的页面结构和安全区域处理",
      icon: "i-mdi-view-dashboard-outline",
      color: "#45b7d1",
      category: "layout",
      hasDemo: false,
      status: "developing",
      version: "1.1.0",
      tags: ["布局", "结构", "安全区"],
    },
    {
      id: "c_tabbar",
      name: "C_Tabbar",
      order: "04",
      path: "/pages/demo/04-tabbar/index",
      description: "底部导航栏组件，支持自定义图标、文字显示和路由跳转",
      icon: "i-mdi-tab",
      color: "#96ceb4",
      category: "navigation",
      hasDemo: false,
      status: "developing",
      version: "1.0.5",
      tags: ["导航", "底部", "Tab"],
    },
  ];

  componentList.value = backupComponents;
  dataInfo.value = {
    version: "1.0.0-backup",
    generatedAt: new Date().toISOString(),
    scanMode: "backup",
    total: backupComponents.length,
    completed: backupComponents.filter((c) => c.status === "completed").length,
    developing: backupComponents.filter((c) => c.status === "developing")
      .length,
  };
};

const formatTime = (isoString) => {
  try {
    const date = new Date(isoString);
    return date.toLocaleString("zh-CN", {
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return "未知";
  }
};

const filterByCategory = (categoryKey) => {
  selectedCategory.value =
    categoryKey === selectedCategory.value ? "all" : categoryKey;
  statusFilter.value = "all"; // 重置状态筛选
};

const filterByStatus = (status) => {
  statusFilter.value = status === statusFilter.value ? "all" : status;
  selectedCategory.value = "all"; // 重置分类筛选
};

const showAllComponents = () => {
  selectedCategory.value = "all";
  statusFilter.value = "all";
};

const navigateToDemo = (component) => {
  if (component.hasDemo) {
    uni.navigateTo({ url: component.path });
  } else {
    uni.showModal({
      title: "即将推出",
      content: `${component.name} 组件演示页面正在开发中！\n\n路径: ${component.path}`,
      showCancel: false,
      confirmText: "知道了",
    });
  }
};

const getStatusClass = (status) => {
  const statusClasses = {
    completed: "bg-green-100 text-green-600",
    developing: "bg-orange-100 text-orange-600",
    deprecated: "bg-red-100 text-red-600",
  };
  return statusClasses[status] || "bg-gray-100 text-gray-600";
};

const getStatusText = (status) => {
  const statusTexts = {
    completed: "已完成",
    developing: "开发中",
    deprecated: "已废弃",
  };
  return statusTexts[status] || "未知";
};

const getEmptyStateText = () => {
  if (selectedCategory.value !== "all" && statusFilter.value !== "all") {
    return `该分类下暂无${
      statusFilter.value === "completed" ? "已完成" : "开发中"
    }的组件`;
  } else if (selectedCategory.value !== "all") {
    return "该分类下暂无组件";
  } else if (statusFilter.value !== "all") {
    return `暂无${
      statusFilter.value === "completed" ? "已完成" : "开发中"
    }的组件`;
  } else {
    return "还没有添加任何组件演示";
  }
};

onMounted(loadComponentData);
</script>

<style lang="scss" scoped>
.component-management {
  background: #f8fafc;
  min-height: 100vh;
}

.intro-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.category-card {
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover,
  &.category-active {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  }
}

.component-card {
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
    border-color: #409eff;
  }
}

.filter-btn,
.stat-card {
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    transform: scale(1.05);
  }
}

.icon-wrapper,
.component-number {
  transition: all 0.3s ease;
}

.component-card:hover .icon-wrapper,
.component-card:hover .component-number {
  transform: scale(1.1);
}

.tag {
  transition: all 0.3s ease;

  &:hover {
    background-color: #409eff;
    color: white;
  }
}

.dev-tip-card {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.text-blue-600 {
  color: #2563eb;
}
.text-green-600 {
  color: #059669;
}
.text-orange-600 {
  color: #ea580c;
}
.text-purple-600 {
  color: #7c3aed;
}
</style>
